"use client"

import React, { createContext, useContext, useState, useCallback, ReactNode } from 'react'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Drawer, DrawerContent, DrawerDescription, DrawerFooter, DrawerHeader, DrawerTitle } from '@/components/ui/drawer'
import { Button } from '@/components/ui/button'

interface ModalState {
  open: boolean
  title?: string
  description?: string
  content?: ReactNode
  size?: 'sm' | 'md' | 'lg' | 'xl'
  onConfirm?: () => void
  onCancel?: () => void
  confirmText?: string
  cancelText?: string
  type: 'dialog' | 'drawer'
}

interface ModalContextType {
  modals: Record<string, ModalState>
  openModal: (id: string, config: Omit<ModalState, 'open'>) => void
  closeModal: (id: string) => void
}

const ModalContext = createContext<ModalContextType | undefined>(undefined)

export const useModal = (id: string = 'default') => {
  const context = useContext(ModalContext)
  if (!context) {
    throw new Error('useModal must be used within a ModalProvider')
  }

  const modal = context.modals[id] || { open: false, type: 'dialog' as const }

  const openDialog = useCallback((config: {
    title?: string
    description?: string
    content?: ReactNode
    size?: 'sm' | 'md' | 'lg' | 'xl'
    onConfirm?: () => void
    onCancel?: () => void
    confirmText?: string
    cancelText?: string
  }) => {
    context.openModal(id, { ...config, type: 'dialog' })
  }, [context, id])

  const openDrawer = useCallback((config: {
    title?: string
    description?: string
    content?: ReactNode
    onConfirm?: () => void
    onCancel?: () => void
    confirmText?: string
    cancelText?: string
  }) => {
    context.openModal(id, { ...config, type: 'drawer' })
  }, [context, id])

  const close = useCallback(() => {
    context.closeModal(id)
  }, [context, id])

  return {
    ...modal,
    openDialog,
    openDrawer,
    close,
    isOpen: modal.open
  }
}

export const ModalProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [modals, setModals] = useState<Record<string, ModalState>>({})

  const openModal = useCallback((id: string, config: Omit<ModalState, 'open'>) => {
    setModals(prev => ({
      ...prev,
      [id]: { ...config, open: true }
    }))
  }, [])

  const closeModal = useCallback((id: string) => {
    setModals(prev => ({
      ...prev,
      [id]: { ...prev[id], open: false }
    }))
    // 延迟清理，让动画完成
    setTimeout(() => {
      setModals(prev => {
        const newModals = { ...prev }
        if (newModals[id] && !newModals[id].open) {
          delete newModals[id]
        }
        return newModals
      })
    }, 300)
  }, [])

  const getMaxWidth = (size?: string) => {
    switch (size) {
      case 'sm': return 'max-w-sm'
      case 'md': return 'max-w-md'
      case 'lg': return 'max-w-lg'
      case 'xl': return 'max-w-xl'
      default: return 'max-w-md'
    }
  }

  return (
    <ModalContext.Provider value={{ modals, openModal, closeModal }}>
      {children}
      
      {/* 渲染所有活跃的模态框 */}
      {Object.entries(modals).map(([id, modal]) => {
        if (!modal.open) return null

        const handleConfirm = () => {
          modal.onConfirm?.()
          closeModal(id)
        }

        const handleCancel = () => {
          modal.onCancel?.()
          closeModal(id)
        }

        if (modal.type === 'dialog') {
          return (
            <Dialog key={id} open={modal.open} onOpenChange={(open) => !open && closeModal(id)}>
              <DialogContent className={getMaxWidth(modal.size)}>
                {(modal.title || modal.description) && (
                  <DialogHeader>
                    {modal.title && <DialogTitle>{modal.title}</DialogTitle>}
                    {modal.description && <DialogDescription>{modal.description}</DialogDescription>}
                  </DialogHeader>
                )}
                
                {modal.content && (
                  <div className="py-4">
                    {modal.content}
                  </div>
                )}
                
                {(modal.onConfirm || modal.onCancel) && (
                  <DialogFooter>
                    {modal.onCancel && (
                      <Button variant="outline" onClick={handleCancel}>
                        {modal.cancelText || '取消'}
                      </Button>
                    )}
                    {modal.onConfirm && (
                      <Button onClick={handleConfirm}>
                        {modal.confirmText || '确认'}
                      </Button>
                    )}
                  </DialogFooter>
                )}
              </DialogContent>
            </Dialog>
          )
        }

        if (modal.type === 'drawer') {
          return (
            <Drawer key={id} open={modal.open} onOpenChange={(open) => !open && closeModal(id)}>
              <DrawerContent>
                {(modal.title || modal.description) && (
                  <DrawerHeader>
                    {modal.title && <DrawerTitle>{modal.title}</DrawerTitle>}
                    {modal.description && <DrawerDescription>{modal.description}</DrawerDescription>}
                  </DrawerHeader>
                )}
                
                {modal.content && (
                  <div className="px-4 py-2 flex-1">
                    {modal.content}
                  </div>
                )}
                
                {(modal.onConfirm || modal.onCancel) && (
                  <DrawerFooter>
                    <div className="flex gap-2">
                      {modal.onConfirm && (
                        <Button onClick={handleConfirm} className="flex-1">
                          {modal.confirmText || '确认'}
                        </Button>
                      )}
                      {modal.onCancel && (
                        <Button variant="outline" onClick={handleCancel} className="flex-1">
                          {modal.cancelText || '取消'}
                        </Button>
                      )}
                    </div>
                  </DrawerFooter>
                )}
              </DrawerContent>
            </Drawer>
          )
        }

        return null
      })}
    </ModalContext.Provider>
  )
}

// 便捷的hooks
export const useConfirmDialog = () => {
  const modal = useModal('confirm')
  
  const confirm = useCallback((config: {
    title: string
    description?: string
    onConfirm: () => void
    confirmText?: string
    cancelText?: string
  }) => {
    modal.openDialog({
      title: config.title,
      description: config.description,
      onConfirm: config.onConfirm,
      onCancel: () => {}, // 空函数，只是为了显示取消按钮
      confirmText: config.confirmText || '确认',
      cancelText: config.cancelText || '取消',
      size: 'sm'
    })
  }, [modal])

  return { confirm }
}

export const useAlertDialog = () => {
  const modal = useModal('alert')
  
  const alert = useCallback((config: {
    title: string
    description?: string
    confirmText?: string
  }) => {
    modal.openDialog({
      title: config.title,
      description: config.description,
      onConfirm: () => {}, // 空函数，只是为了显示确认按钮
      confirmText: config.confirmText || '确定',
      size: 'sm'
    })
  }, [modal])

  return { alert }
} 